package com.itjiange.springbootinit.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel 工具类
 *
 * @author ItJiange
 * @date 2023/12/5
 */
@Slf4j
public class ExcelUtils {

    /**
     * 将 Excel 文件转换成 csv
     * @param multipartFile
     * @return
     */
    public static String excelTpCsv(MultipartFile multipartFile) {
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:test_excel.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }

        // 获取 Excel 表格中数据
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (Exception e) {
            log.error("表格信息处理错误", e);
        }
        if (list == null) {
            return "";
        }

        // 封装返回结果
        StringBuffer sf = new StringBuffer();
        // 格式化表格中的数据
        LinkedHashMap<Integer, String> columnMap = (LinkedHashMap) list.get(0);
        // 过滤列名数据
        List<String> collected = columnMap.values().stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
        sf.append(StrUtil.join(",", collected)).append('\n');
        // 过滤数据
        int size = list.size();
        for (int i = 1; i < size; i++) {
            Map<Integer, String> dateMap = list.get(i);
            List<String> dateMaps = dateMap.values().stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
            sf.append(StrUtil.join(",", dateMaps)).append('\n');
        }
        return sf.toString();
    }
}
